//
//  StoreDetailVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/5.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import Eureka
import Alamofire
import SVProgressHUD

class StoreDetailVC: FormViewController {
    
    
    let lists = ["商号简称", "商号全称", "联系人", "手机", "电话", "主营", "简介", "地址"]
    let refreshControl = UIRefreshControl()
    let storeHelper = StoreVCHelper()
    var enableEditting = false
    var params: [String: Any] = ["sessionId": Store.sessionID!, "storeId": "\(Store.storeId!)"]
    let queue = DispatchQueue(label: "loadImageQueue")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        // insert right bar button
        let button = UIButton(type: .system)
        button.setTitle("编辑", for: .normal)
        button.tintColor = .white
        button.addTarget(self, action: #selector(editButtonTapped(_:)), for: .touchUpInside)
        let editItem = UIBarButtonItem(customView: button)
        
        navigationItem.rightBarButtonItem = editItem

        tableView.insertSubview(refreshControl, at: 0)
        refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
        reloadData()
        
        TextRow.defaultCellUpdate = { cell, row in
            cell.isSelected = false
            cell.textField.isEnabled = self.enableEditting
            
        }
        PhoneRow.defaultCellUpdate = { cell, row in
            cell.textField.isEnabled = self.enableEditting
        }

        ImageRow.defaultCellUpdate = { cell, row in
            cell.isUserInteractionEnabled = self.enableEditting
            cell.height = { 65 }
            cell.accessoryView?.layer.cornerRadius = 30
            cell.accessoryView?.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
        }
        
        form +++
            Section("商店图标")
            
            <<< ImageRow() { row in
                row.title = "Logo"
            }
                .onChange({ (row) in
                    let logo = self.convertToBase64(row.value!)
                    self.params["logo"] = logo!
                })
            
            +++ Section("商店简介")
            
            <<< TextRow() {
                $0.title = lists[0]
            }
                .onChange({ (row) in
                    self.params["alias"] = row.value ?? ""
                })
                .cellUpdate({ (cell, row) in
                    row.value = Store.alias ?? ""
                })
            
            
            
            <<< TextRow() {
                $0.title = lists[1]
            }
                .onChange({ (row) in
                    self.params["name"] = row.value ?? ""
                })
                .cellUpdate({ (cell, row) in
                    row.value = Store.name ?? ""
                })
            <<< TextRow() {
                $0.title = lists[2]
            }
                .onChange({ (row) in
                    self.params["contact"] = row.value ?? ""
                })
                .cellUpdate({ (cell, row) in
                    row.value = Store.contact ?? ""
                })
            <<< PhoneRow() {
                $0.title = lists[3]
            }
                .onChange({ (row) in
                    self.params["phone"] = row.value ?? ""
                })
                .cellUpdate({ (cell, row) in
                    row.value = Store.phone ?? ""
                })
            <<< TextRow() {
                $0.title = lists[4]
            }
                .onChange({ (row) in
                    self.params["telephone"] = row.value ?? ""
                })
                .cellUpdate({ (cell, row) in
                    row.value = Store.telephone ?? ""
                })
            <<< TextRow() {
                $0.title = lists[5]
            }
                .onChange({ (row) in
                    self.params["mainBusiness"] = row.value ?? ""
                })
                .cellUpdate({ (cell, row) in
                    row.value = Store.mainBusiness ?? ""
                })
            <<< TextRow() {
                $0.title = lists[6]
                $0.cell.height = { 100 }
            }
                .cellUpdate({ (cell, row) in
                    row.value = Store.description ?? ""
                })
                .onChange({ (row) in
                    self.params["description"] = row.value ?? ""
                })
            
            <<< TextRow() {
                $0.title = lists[7]
        }
                .onChange({ (row) in
                    self.params["address"] = row.value ?? ""
                })
                .cellUpdate({ (cell, row) in
                    row.value = Store.address ?? ""
                })
        
        
    }
    func loadImage() {
        guard Store.logo! != "" else {
            return
        }
        Alamofire.request(URL(string: Store.logo!)!).responseImage(completionHandler: { (response) in
            if response.result.error == nil {
                DispatchQueue.main.async {
                    if let image = response.result.value {
                        let row = self.form.allRows[0] as! ImageRow
                        row.value = image
                        row.cell.update()
                    }
                }
            }
        })
    }
    
    
    @objc func editButtonTapped(_ button: UIButton!) {
        enableEditting = !enableEditting
        let title = enableEditting ? "完成" : "编辑"
        if !enableEditting {
            upload()
        }
        button.setTitle(title, for: .normal)
        tableView.reloadData()
    }
    func upload() {
        view.isUserInteractionEnabled = false
        SVProgressHUD.show()
        storeHelper.edit(parameters: params) { (success) in
            self.view.isUserInteractionEnabled = true
            if success {
                SVProgressHUD.showSuccess(withStatus: "")
            } else {
                SVProgressHUD.showError(withStatus: "发生错误")
            }
            SVProgressHUD.dismiss()
        }
        
    }
    
    func reloadData() {

        if Store.authority! == 0 {
            storeHelper.visit(completeHandler: { (success) in
                self.refreshControl.endRefreshing()
                if success {
                    self.queue.async {
                        self.loadImage()
                    }
                    self.tableView.reloadData()
                }
            })
        } else {
            storeHelper.find(completeHandler: { (success) in
                self.refreshControl.endRefreshing()
                if success {
                    self.queue.async {
                        self.loadImage()
                    }
                    self.tableView.reloadData()
                }
            })
        }
    }
    
    
    @objc
    func refresh(_ refreshView: UIRefreshControl) {
        reloadData()
    }
}
extension StoreDetailVC: LoginDelegate {
    func prepareMainVC(state: AppState) {
        switch App.state {
        case .AdminState:
            let storyBoard = UIStoryboard(name: "MainStoryboard", bundle: nil)
            let mainVC = storyBoard.instantiateViewController(withIdentifier: "MainViewController")
            let nv = UINavigationController(rootViewController: mainVC)
            self.revealViewController().setFront(nv, animated: true)
        case .ApplyState:
            let navigationVC = UINavigationController(rootViewController: ApplyStoreVC())
            self.revealViewController().setFront(navigationVC, animated: true)
        case .MemberState:
            let navigationVC = UINavigationController(rootViewController: MemberVC())
            self.revealViewController().setFront(navigationVC, animated: true)
        case .none:
            break
        }
    }
    func loginSuccess(from state: AppState) {
        prepareMainVC(state: state)
    }
}

